package com.study.system.utils;

import com.study.model.system.SysDept;
import java.util.List;
import java.util.stream.Collectors;

public class DeptHelper {
    public static List<SysDept> tree(List<SysDept> depts){
        List<SysDept> res = depts.stream()
                .filter(dept -> dept.getParentId() == 0)
                .map(dept -> setChildren(dept, depts)).collect(Collectors.toList());
        return res;
    }

    public static SysDept setChildren(SysDept dept, List<SysDept> deptList){
        SysDept res = new SysDept();
        res.setChildren(dept.getChildren());
        res.setLeader(dept.getLeader());
        res.setName(dept.getName());
        res.setParentId(dept.getParentId());
        res.setPhone(dept.getPhone());
        res.setSortValue(dept.getSortValue());
        res.setStatus(dept.getStatus());
        res.setTreePath(dept.getTreePath());
        res.setCreateTime(dept.getCreateTime());
        res.setId(dept.getId());
        res.setIsDeleted(dept.getIsDeleted());
        res.setParam(dept.getParam());
        res.setUpdateTime(dept.getUpdateTime());
        //CopyUtil.copyPropertiesIgnoreNull(dept,res);
        //BeanUtils.copyProperties(dept,res); //报错原因，dept中children属性为null，报错java.lang.reflect.InvocationTargetException
        int a = 1;
        List<SysDept> children = deptList.stream()
                .filter(subDept -> subDept.getParentId() == Long.parseLong(dept.getId()))
                .map(subDept -> setChildren(subDept, deptList)).collect(Collectors.toList());
        res.setChildren(children);
        return res;
    }
}
